package com.benyi.byiee.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.benyi.byiee.dao.mappers.UserAccountMapper;
import com.benyi.byiee.dao.mappers.EnterpriseInfoMapper;
import com.benyi.byiee.model.db.EnterpriseInfo;
import com.benyi.byiee.model.db.UserAccount;
import com.benyi.util.Config;
import com.benyi.util.SplitUtil;
import com.benyi.util.Tools;
import com.benyi.util.bean.Page;
import com.benyi.util.bean.PageReq;
import com.benyi.util.bean.ServiceException;

import jakarta.annotation.Resource;

@Service
public class EnterpriseService {
	
	private static Logger log = LoggerFactory.getLogger(EnterpriseService.class);
	
	@Resource(name="config")
	private Config config;
	
	@Autowired
	private EnterpriseInfoMapper epMapper;
	
	@Autowired
	private UserAccountMapper userMapper;
	
	public EnterpriseInfo freshTime(String uuid) throws ServiceException {
		try {
			EnterpriseInfo d = epMapper.selectByUuid(uuid);
			if(d != null ) {
				//d.setRefreshTm(System.currentTimeMillis());
				epMapper.freshTime(d);
			} 
			return d;
		}catch(Exception e) {
			throw new ServiceException("fresh-exception",e.getMessage());
		} 
	}
	
	public EnterpriseInfo updateFull(EnterpriseInfo com) throws ServiceException {
		try {
			epMapper.updateByUuid(com); //全面更新
			return com;
		}catch(Exception e) {
			throw new ServiceException("update-exception",e.getMessage());
		} 
	}
	
	
	public EnterpriseInfo updatePart(EnterpriseInfo com) throws ServiceException {
		try {
			epMapper.updateByUuidSelective(com);  //为空的字段不更新
			return com;
		}catch(Exception e) {
			throw new ServiceException("update-exception",e.getMessage());
		} 
	}
	
	public EnterpriseInfo insert(EnterpriseInfo com) throws ServiceException {
		try {
			int rows = epMapper.insert(com);
			boolean ok = false;
			if(rows == 1) {
				rows =  updateUuid(com); 
				if(rows == 1) {
					ok = true;
				}
			} 
			if(ok == false) {
				throw new ServiceException("insert fail","Insert enterprise failed, update rows is not euqal 1!");
			}
			return com;
		}catch(Exception e) {
			throw new ServiceException("insert-exception",e.getMessage());
		} 
	}
	
	private int updateUuid(EnterpriseInfo d) {
		long rid = d.getRid();
		String uuid = Tools.md5(String.valueOf(rid));
		d.setUuid(uuid.toLowerCase());
		int rows = epMapper.updateUuid(d);
		return rows;
	}
	
	public Page<EnterpriseInfo> queryByKeys(PageReq<String> req) throws ServiceException {
		String []ks = getKeys(req.getQuery());
		int kNum = config.getInt("query_max_keys");
		if(kNum<1) {
			kNum = 3;
		}
		if(ks!=null && ks.length > kNum) {
			String []ky = new String[kNum];
			for(int i=0;i<ky.length;i++) {
				ky[i] = ks[i];
			}
			ks = ky;
		}
		try {
			int count = epMapper.countByKeys(ks);
			req.verify(); 
			List<EnterpriseInfo>  list = epMapper.queryByKeys(ks, req.getFrom(), req.getPageLength());
			for(EnterpriseInfo d:list) {
				if(d.getUuid() == null || d.getUuid().length() < 12) {
					updateUuid(d); //确保 uuid 不为空
				}
				d.setRid(null); //隐藏rid
			}
			Page<EnterpriseInfo> page = new Page<EnterpriseInfo>();
			page.setRows(list, req, count); 
			return page;
		}catch(Exception e) {
			log.error("query page exception",e);
			throw new ServiceException("enterprise_page_faile","获取企业分页数据异常:"+e.getMessage());
		}  
	}
	
	private String[] getKeys(String line) {
		
		if(line==null || line.length()==0) { 
			String []k=new String[0];
			return k;
		}
		String []ks = SplitUtil.split(line);
		
		int num = 0;
		if(ks !=null) {
			for(int i=0;i<ks.length;i++) {
				if(ks[i]!=null && ks[i].length()>0) {
					num++; 
					if(i<ks.length-1) {
						for(int j=i+1;j<ks.length;j++) {
							if(ks[i].equalsIgnoreCase(ks[j])) {
								ks[j]=null; //把相等的设置为 null
							}
						}
					} 
				}else {
					ks[i] = null;
				}
			}
		}
		String []keys = null;
		if(num>0) {
			keys = new String[num];
			num = 0;
			for(int i=0;i<ks.length;i++) {
				if(ks[i]!=null) {
					keys[num] = ks[i];
					num++;  
				}
			}
		}
		return keys;
	}
	
	public EnterpriseInfo queryByUSerMail(String email) throws ServiceException {
		try {
			UserAccount u = userMapper.selectByEmail(email);
			if(u==null) {
				throw new ServiceException("email-not-exist","User not find by email:"+email);
			}
			EnterpriseInfo d = epMapper.selectByUserId(u.getRid()); 
			return d;
		}catch(Exception e) {
			throw new ServiceException("fresh-exception",e.getMessage());
		} 
	}
}
